package com.tang.plugin;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.intellij.ide.util.PropertiesComponent;
import com.tang.plugin.model.Module;

import java.util.ArrayList;
import java.util.List;

public class Config {

    private static final String KEY_TEMPLATE = "template";
    private static final String KEY_INITED = "inited";

    public static final Gson GSON = new GsonBuilder().setLenient().create();
    private static final PropertiesComponent STORE = PropertiesComponent.getInstance();

    public static void clear() {
        STORE.unsetValue(KEY_TEMPLATE);
    }

    public static List<Module> loadModuleTemplates() {
        List<Module> result = new ArrayList<>();
        String[] arr = STORE.getValues(KEY_TEMPLATE);
        if (STORE.getBoolean(KEY_INITED)) {
            result.add(Module.createRouteModule());
        }
        if (arr == null || arr.length == 0) {
            return result;
        }
        for (String s : arr) {
            if (s != null && !s.isEmpty()) {
                try {
                    Module module = GSON.fromJson(s, Module.class);
                    module.initTemplate();
                    result.add(module);
                } catch (Exception e) {
                    e.printStackTrace();
                    clear();
                    return result;
                }
            }
        }
        return result;
    }

    public static void saveModuleTemplates(List<Module> templates) {
        if (templates.isEmpty()) {
            clear();
            return;
        }
        List<String> t = new ArrayList<>();
        templates.forEach((it) -> t.add(GSON.toJson(it)));
        STORE.setValue(KEY_INITED, false, false);
        STORE.setValues(KEY_TEMPLATE, t.toArray(new String[0]));
    }
}
